package org.uim.cricket.entities.parser.impl;

import org.apache.commons.lang3.StringEscapeUtils;
import org.uim.cricket.entities.FullPlayer;
import org.uim.cricket.entities.parser.PlayerEntityParsable;
import org.uim.cricket.entities.parser.filters.PlayerDetailFilterable;
import org.uim.cricket.util.HTMLStringUtils;
import org.uim.cricket.util.MyStringUtils;

public class HTMLPlayerPageParser implements PlayerEntityParsable {

	private PlayerDetailFilterable playerFilter = null;
	private String[] ignoreAttributes = null;
	
	public HTMLPlayerPageParser(PlayerDetailFilterable pFilter) {
		this.playerFilter = pFilter;
	}
	
	@Override
	public FullPlayer parsePlayer(StringBuilder source) {
		FullPlayer player = new FullPlayer();
		
		int pos = source.indexOf("<div class=\"pnl490M\">");
		if (pos < 0) return null;
		String src = source.substring(pos);
		src = src.replaceAll("&nbsp;", "");
		
		String shortName = MyStringUtils.inBetween(src, "<h1>", "</h1>");
		if (shortName == null) return null;
		shortName = HTMLStringUtils.cleanHTMLTags(shortName);
		shortName = StringEscapeUtils.unescapeHtml4(shortName).trim();
		player.setShortName(shortName);
		
		String allmteams = MyStringUtils.inBetween(src, "<h3 ", "</h3>");
		if (allmteams != null) {
			allmteams = HTMLStringUtils.cleanHTMLTags("<h3 " + allmteams);
			player.setCountry(allmteams);
		}
		
		String[] pinfos = MyStringUtils.splitInBetween(src, "<p class=\"ciPlayerinformationtxt\">", "</p>");
		if (pinfos == null) return player;
		
		for (int i=0; i<pinfos.length; i++) {
			String attrib = MyStringUtils.inBetween(pinfos[i], "<b>", "</b>");
			if (attrib == null) continue;
			if (this.containInIgnoreList(attrib)) continue;
			
			pos = pinfos[i].indexOf("</b>");
			if (pos < 0) continue;
			
			pinfos[i] = pinfos[i].substring(pos + "</b>".length()).trim();
			String value = HTMLStringUtils.cleanHTMLTags(pinfos[i]);
			
			if (this.playerFilter != null) {
				this.playerFilter.filterAttribute(player, attrib, value);
			} else {
				player.addNewAttribute(attrib, value);
			}
		}
		
		return player;
	}

	private boolean containInIgnoreList(String attrib) {
		if (this.ignoreAttributes == null) return false;
		for (int i=0; i<this.ignoreAttributes.length; i++) {
			if (attrib.startsWith(this.ignoreAttributes[i])) return true;
		}
		return false;
	}
	
	public void setPlayerFilter(PlayerDetailFilterable playerFilter) {
		this.playerFilter = playerFilter;
	}
	
	public PlayerDetailFilterable getPlayerFilter() {
		return playerFilter;
	}
	
	public void setIgnoreAttributes(String[] ignoreAttributes) {
		this.ignoreAttributes = ignoreAttributes;
	}
	
	public String[] getIgnoreAttributes() {
		return ignoreAttributes;
	}
	
}
